<template>
  <div
    v-functions="['customer_assign']"
    class="Track"
    style="display: inline-block"
  >
    <template v-if="!noBtn">
      <el-tooltip
        v-if="wechatShow"
        effect="dark"
        content="分配"
        placement="top"
      >
        <i
          @click="openDialog"
          style="
            color: #767e91;
            margin-left: 14px;
            font-size: 12px;
            cursor: pointer;
          "
          class="V7_iconfont V7_iconV7tubiao_fenpei"
        ></i>
      </el-tooltip>
      <el-button v-else @click="openDialog" size="mini">分配</el-button>
    </template>
    <MoveDialog
      :visible.sync="visible"
      :before-close="closeDialog"
      class="formRef"
      width="400px"
      :close-on-click-modal="false"
      append-to-body
    >
      <span
        slot="title"
        style="color: #303753; font-size: 14px; font-weight: 600"
        >分配</span
      >
      <el-form
        ref="formRef"
        class="m7-form"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="所属部门" prop="description">
          <el-cascader
            :clearable="true"
            style="width: 100%"
            @change="resetAgent"
            size="small"
            filterable
            v-model="formData.description"
            :options="departmentTree"
            :props="{
              label: 'name',
              value: '_id',
              checkStrictly: true,
              emitPath: false,
            }"
            :show-all-levels="true"
            placeholder="请选择"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="人员名称" prop="owner" style="margin-bottom: 0px">
          <el-select
            v-model="formData.owner"
            placeholder="请选择"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in AgentList"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" size="mini">取 消</el-button>
        <el-button type="primary" @click="submit" size="mini">确 定</el-button>
      </div>
    </MoveDialog>
  </div>
</template>

<script lang="ts">
/**
 * 分配按钮
 */
import { Component, Vue, Ref, Prop } from 'vue-property-decorator'
import { CommonModule } from '@/store/modules/common'
import MoveDialog from '@/components/globalTool/moveDialog/index.vue'
import { commonAction } from '@/utils/common'
@Component({
  name: 'Track',
  components: {
    MoveDialog
  }
})
export default class Track extends Vue {
  [x: string]: any
  @Ref() private readonly formRef: any
  @Prop() private customerId
  @Prop() private wechatShow
  @Prop({ default: () => false }) private noBtn
  private visible = false
  private formData = {
    description: '',
    owner: ''
  }

  private ids: any = [] // 批量选中
  private condition: any = {} // 全选
  private isBatch: boolean = false // 是否为批量选中

  // 获取部门树
  get departmentTree () {
    return (CommonModule as any).publicCache.departmentTree.tree
  }

  // 获取座席数组
  get AgentList () {
    const list = (CommonModule as any).publicCache.userList
    let filterList: any = []
    if (this.formData.description) {
      filterList = list.filter(v => {
        let departmentId: any = []
        if (v.departmentConfig) {
          departmentId = v.departmentConfig.departmentIdList
        }
        if (departmentId && departmentId.length && departmentId.includes(this.formData.description)) {
          return true
        }
        return false
      })
    } else {
      filterList = list
    }
    return filterList.map(v => ({ name: `${v.agentName} 【${v.agentNumber}】`, _id: v._id }))
  }

  private rules = {
    owner: [{ required: true, trigger: 'change', message: '请选择座席' }]
  }

  // 部门变化重置座席数据
  private resetAgent () {
    this.formData.owner = ''
  }

  // TODO 打开对话框，可以在此填入数据
  public openDialog (ids?: any, condition?: any, batch?: boolean) {
    if (batch) {
      this.isBatch = true
      this.ids = ids
      this.condition = condition
    } else {
      this.isBatch = false
    }
    this.visible = true
  }

  // 关闭对话框
  private closeDialog () {
    this.formRef.clearValidate()
    this.formData = {
      description: '',
      owner: ''
    }
    this.visible = false
  }

  // 提交
  private submit () {
    this.formRef.validate(valid => {
      if (valid) {
        const params = {
          url: this.isBatch ? '/server-crm/action/customer/batchSaveCustomerByAssign' : '/server-crm/action/customer/saveCustomerByAssign',
          method: 'POST',
          data: this.isBatch ? { ...this.formData, ids: this.ids, condition: this.condition } : { ...this.formData, customerId: this.customerId }
        }
        commonAction(params).then(res => {
          if (res.success) {
            this.$message.success('分配成功')
            this.$emit('updateLog', this.formData.owner)
            this.closeDialog()
            if (this.isBatch) {
              this.$emit('clearBatchSelect')
            }
          }
        })
      }
    })
  }
}
</script>
